import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';  // 添加 UnauthorizedException
import { UsersService } from '../users/users.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private usersService: UsersService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET || 'your-secret-key',  // 使用环境变量，与 UsersModule 中的配置一致
    });
  }
  async validate(payload: any) {
    console.log('JWT 验证开始: payload =', payload);  // 日志: 输出 token payload

    const user = await this.usersService.findById(payload.sub);
    
    if (!user) {
      console.error('JWT 验证失败: 用户 ID', payload.sub, '不存在');
      throw new UnauthorizedException('用户不存在或 token 无效');
    }
    
    console.log('JWT 验证成功: 用户 =', user.employeeId, '角色 =', user.role);
    return user;
  }
}